package com.yvon.maple.service.auth.config;

import com.yvon.maple.service.auth.properties.LdapDataProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ldap.core.AuthenticationSource;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;

/**
 * ldap配置
 *
 * @author : Yvon
 * @since : 2022-02-17
 */
@Configuration
@ConditionalOnProperty(prefix = "maple.ldap", value = "enabled", havingValue = "true")
@Slf4j
public class LdapConfig {

    private final LdapDataProperties ldapDataProperties;

    public LdapConfig(LdapDataProperties ldapDataProperties) {
        this.ldapDataProperties = ldapDataProperties;
    }

    @Bean
    public LdapContextSource ldapContextSource(){
        LdapContextSource ldapContextSource=new LdapContextSource();
        ldapContextSource.setCacheEnvironmentProperties(false);
        ldapContextSource.setUrl(ldapDataProperties.getUrl());
        ldapContextSource.setBase(ldapDataProperties.getSearchBase());
        ldapContextSource.setUserDn(ldapDataProperties.getManagerDn());
        ldapContextSource.setPassword(ldapDataProperties.getManagerPassword());
        ldapContextSource.setAuthenticationSource(new AuthenticationSource() {
            @Override
            public String getCredentials() {
                return ldapDataProperties.getManagerPassword();
            }

            @Override
            public String getPrincipal() {
                return ldapDataProperties.getManagerDn();
            }
        });
        return ldapContextSource;
    }

    @Bean
    public LdapTemplate ldapTemplate(){
        log.info("ldapTemplate初始化成功");
        return new LdapTemplate(ldapContextSource());
    }
}
